package com.cqupt.mislab.erpn.commons.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author xhx
 * @Date 2021/4/27 21:19
 */
@Slf4j
public class CSVUtil {
    //Linux服务器
//    public static final String FILE_PATH = "/erp/hd/csv/";
//    Windows
    public static final String FILE_PATH = "C:\\erpnReport\\csv";
    //换行符
    public static final String SEPARATOR = "\n";

    public static File transforFile(MultipartFile multipartFile) throws IOException {

        String path = FILE_PATH + File.separator + multipartFile.getOriginalFilename();
        File file = new File(path);
        if(!file.getParentFile().exists()){
            file.mkdir();
        }
        log.info("将文件转储到本地！");
        multipartFile.transferTo(file);

        return file;
    }

    public static List<List<String>> readApprovedCSV(File csvFile,int columns) throws IOException {
        List<List<String>> results = new ArrayList<>();
        try(FileInputStream fileInputStream = new FileInputStream(csvFile);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        ){
            CSVParser parser = CSVFormat.DEFAULT.parse(bufferedReader);

            int rowIndex = 0;
            for (CSVRecord record:parser.getRecords()) {
                if(record.size() < columns) {
                    throw new IOException();
                }
                if (rowIndex == 0){
                    rowIndex++;
                    continue;
                }
                List<String> result =  new ArrayList<>();
                for(int i = 0; i < columns;i++){
                    result.add(record.get(i));
                }
                results.add(result);
            }

        }catch (IOException e){
            throw new IOException("解析异常！");
        }
        return results;
    }
}
